﻿#include "cdatabasexml.h"
#include <QDir>
#include <QFile>
#include <QVector>
#include <QDomDocument>
#include <QDomElement>

CDatabaseXml::CDatabaseXml()
{
}

QVector<QString> CDatabaseXml::getTableName()
{
    QVector<QString> vec;
    QString sPath = QDir::currentPath();
    sPath += "/config/Database.xml";
    //文件是否存在判断
    QFileInfo info(sPath);
    if(false == info.exists()) return vec;

    //文件打开判断
    QFile file(sPath);
    if(false == file.open(QIODevice::ReadOnly | QFile::Text))
    {
        return vec;
    }

    //读文件
    QString errStr;
    int errLine;
    int errColumn;
    QDomDocument doc;
    if(!doc.setContent(file.readAll(), false, &errStr, &errLine, &errColumn))
    {
        file.close();
        return vec;
    }
    file.close();
    //解析文件
    QDomElement root = doc.documentElement();
    QDomNodeList dList = root.elementsByTagName("Tables");
    for(int i=0; i<dList.size(); ++i)
    {
        QDomElement ele = dList.at(i).toElement();
        QDomNodeList dTable = ele.elementsByTagName("Table");
        for (int j = 0; j < dTable.size(); ++j)
        {
            QDomElement e = dTable.at(j).toElement();
            QString strName = e.attribute("Name");
            vec.append(strName);
        }
    }
    return vec;
}

QVector<CDbTableInfo> CDatabaseXml::getTableInfo()
{
    QVector<CDbTableInfo> vec;
    QString sPath = QDir::currentPath();
    sPath += "/config/Database.xml";
    //文件是否存在判断
    QFileInfo info(sPath);
    if(false == info.exists()) return vec;

    //文件打开判断
    QFile file(sPath);
    if(false == file.open(QIODevice::ReadOnly | QFile::Text))
    {
        return vec;
    }

    //读文件
    QString errStr;
    int errLine;
    int errColumn;
    QDomDocument doc;
    if(!doc.setContent(file.readAll(), false, &errStr, &errLine, &errColumn))
    {
        file.close();
        return vec;
    }
    file.close();
    //解析文件
    QDomElement root = doc.documentElement();
    QDomNodeList dList = root.elementsByTagName("Tables");
    for(int i=0; i<dList.size(); ++i)
    {
        QDomElement ele = dList.at(i).toElement();
        QDomNodeList dTable = ele.elementsByTagName("Table");
        for (int j = 0; j < dTable.size(); ++j)
        {
            QDomElement e = dTable.at(j).toElement();
            CDbTableInfo info;
            info.nIndex = e.attribute("Index").toInt();
            info.sMode = e.attribute("Mode");
            info.sTableName = e.attribute("Name");
            info.sDesc = e.attribute("Desc");
            vec.append(info);
        }
    }
    return vec;
}
